package com.mioto.ld.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mioto.ld.aop.anno.BizLogAnno;
import com.mioto.ld.aop.model.BaseRequest;
import com.mioto.ld.aop.model.RequestErrorInfo;
import com.mioto.ld.aop.model.RequestInfo;
import com.mioto.ld.module.log.model.BizLog;
import com.mioto.ld.module.log.service.IBizLogService;
import com.mioto.ld.utils.BaseUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.wiring.BeanWiringInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mioto-qinxj
 * @date 2024/4/11
 * @desc 客户端请求日志打印
 */
@Component
@Aspect
@Slf4j
public class RequestLogAspect {
    private String language;

    @Resource
    private IBizLogService bizLogService;

    @Pointcut("execution(* com.mioto.ld.module.*.controller..*(..))")
    public void requestServer() {
    }

    @Around("requestServer()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setBaseRequest(buildRequest(proceedingJoinPoint));
        requestInfo.setTimeCost(System.currentTimeMillis() - start);
        log.debug("Request Info: {}", JSONUtil.parseObj(requestInfo));
        saveBizLog(requestInfo.getBaseRequest().getIp(),"",proceedingJoinPoint);
        return result;
    }

    @AfterThrowing(pointcut = "requestServer()", throwing = "e")
    public void doAfterThrow(JoinPoint joinPoint, RuntimeException e) {
        RequestErrorInfo requestErrorInfo = new RequestErrorInfo();
        requestErrorInfo.setBaseRequest(buildRequest(joinPoint));
        requestErrorInfo.setErrorMsg(e.toString());
        log.error("Error Request Info: {}", JSONUtil.parseObj(requestErrorInfo));
        saveBizLog(requestErrorInfo.getBaseRequest().getIp(),"系统异常",joinPoint);
    }

    private void saveBizLog(String ip,String desc,JoinPoint joinPoint){
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        BizLogAnno bizLogAnno = method.getAnnotation(BizLogAnno.class);
        if (ObjectUtil.isNotNull(bizLogAnno)) {
            BizLog bizLog = new BizLog();
            bizLog.setIp(ip);
            bizLog.setModuleName(bizLogAnno.moduleName().getDesc(language));
            bizLog.setOperationType(bizLogAnno.operationType().getDesc(language));
            bizLog.setDesc(desc);
            bizLogService.insert(bizLog);
        }
    }

    private BaseRequest buildRequest(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        BaseRequest baseRequest = new BaseRequest();
        baseRequest.setIp(request.getRemoteAddr());
        baseRequest.setUrl(request.getRequestURL().toString());
        baseRequest.setHttpMethod(request.getMethod());
        baseRequest.setClassMethod(String.format("%s.%s", joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName()));
        baseRequest.setRequestParams(getRequestParamsByJoinPoint(joinPoint));
        return baseRequest;
    }

    private Map<String, Object> getRequestParamsByJoinPoint(JoinPoint joinPoint) {
        //参数名
        String[] paramNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
        //参数值
        Object[] paramValues = joinPoint.getArgs();
        return buildRequestParam(paramNames, paramValues);
    }

    private Map<String, Object> buildRequestParam(String[] paramNames, Object[] paramValues) {
        Map<String, Object> requestParams = new HashMap<>();
        for (int i = 0; i < paramNames.length; i++) {
            Object value = paramValues[i];
            //如果是文件对象
            if (value instanceof MultipartFile) {
                MultipartFile file = (MultipartFile) value;
                //获取文件名
                value = file.getOriginalFilename();
            }else if (value instanceof HttpServletResponse){
                value = "response";
            }else if (value instanceof HttpServletRequest){
                value = "request";
            }
            requestParams.put(paramNames[i], value);
        }

        return requestParams;
    }

    @Value("${language}")
    public void setLanguage(String language) {
        this.language = language;
    }
}
